<template>
  <div ref="chartRef" :style="{ width, height }"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  }
})

const chartRef = ref(null)
let chartInstance = null

const initChart = () => {
  if (chartInstance) return

  chartInstance = echarts.init(chartRef.value)

  // 禁用 mousewheel 缩放功能
  chartInstance.setOption({
    ...props.option,
    dataZoom: [
      {
        type: 'inside',
        zoomOnMouseWheel: false, // 禁用鼠标滚轮缩放
      },
    ],
  })

  // 强制将 wheel 事件标记为 passive
  const zr = chartInstance.getZr()
  const originalOn = zr.on
  zr.on = function (eventName, handler, options) {
    if (eventName === 'wheel') {
      options = { passive: true } // 强制标记为 passive
    }
    return originalOn.call(this, eventName, handler, options)
  }
}

const resizeChart = () => {
  chartInstance?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  chartInstance?.dispose()
})

watch(
    () => props.option,
    (newVal) => {
      if (chartInstance) {
        chartInstance.setOption(newVal)
      }
    },
    { deep: true }
)
</script>